<script lang="ts" setup>
// import type { WafListItem } from '@/apis/model/waf'
// import type { CloudFilterBarState } from '@/components/filter-bar/types'
import { Message } from '@arco-design/web-vue'
import Sortable from 'sortablejs'
// import {
//   deleteApiWafApi,
//   getApiWafQueryApi,
//   updateApiWafPriorityApi,
//   updateApiWafStatusApi,
// } from '@/apis/modules/waf'

import {
  deleteCdnNodeWafIdApi,
  getCdnNodeWafsApi,
  updateCdnNodeWafPriorityApi,
  updateCdnNodeWafStatusApi,
} from '@/apis/modules/cdn'
// import useTableColumn from './column'
import { A_EXECUTION_TYPE, executionOptions } from '@/constants/cdn-node'
// import { useConfigStore } from '@/stores/config'
import { commonTableProps } from '@/utils/table'
import NodeDeploy from '../../../node-deploy/NodeDeploy.vue'
import EditorDialog from './dialogs/EditorDialog.vue'
import useConfig from './useConfig'

const execution = ref(0)
const { searchSchema, tableColumns } = useConfig()
const tableRef = ref()
const params = ref({
  order: 'asc',
  sort: 'priority',
  // sort: 'created_at',
  scope: 3,
  module: 2,
  action: 0,
})

const {
  visible: editorDialogVisible,
  open: openEditorDialog,
  data: editorDialogData,
} = usePopup()
const {
  visible: deployDialogVisible,
  open: openDeployDialog,
  data: deployDialogData,
} = usePopup()

// const { columns, filterSchemes } = useTableColumn()
const { data, loading, run, pagination } = useListRequest(getCdnNodeWafsApi, {
  params,
  immediate: true,
})

const { createSortChange } = useTable(run, data)
const onSorterChange = createSortChange(params)
function handleBeforeChange(status: number, row: WafListItem) {
  return new Promise((resolve, reject) => {
    updateCdnNodeWafStatusApi({ id: row.id, status } as any)
      .then(() => {
        row.status = row.status === 1 ? 2 : 1
        resolve(void 0)
      })
      .finally(() => {
        // reject(false)
      })
  })
}
// 删除规则
function handleDelete(row: any) {
  ModalHelper.error(
    {
      title: '删除规则',
      content: `确认删除规则 “${row?.name}” ？`,
      okText: '删除',
    },
    async () => {
      await deleteCdnNodeWafIdApi({ id: row?.id })
      Message.success('操作成功')
      run!()
    },
  )
}
async function changeRule(id: string, priority: number) {
  await updateCdnNodeWafPriorityApi({ id, priority })
  Message.success('操作成功')
  run()
}
onMounted(async () => {
  const customRulesId = localStorage.getItem('customRulesId')
  if (customRulesId) {
    params.value.id = customRulesId
    localStorage.setItem('customRulesId', '')
  }
  await nextTick()
  const el = (tableRef.value.$el as HTMLElement).querySelector('tbody')
  Sortable.create(el, {
    animation: 300,
    // 设置指定列作为拖拽
    handle: '.drag-icon',
    forceFallBack: true,
    onEnd(evt: { newIndex: number, oldIndex: number }) {
      const { newIndex, oldIndex } = evt
      if (newIndex === oldIndex) {
        return
      }
      const id = data.value[oldIndex].id!
      const priority = data.value[newIndex].priority!
      changeRule(id, priority)
    },
  })
  useConfigStore().getCondition({ module: 2 })
})
</script>

<template>
  <main-container
    :loading="loading"
    :pagination="pagination"
    @run="run"
  >
    <div class="mb-4 mt-6 flex space-x-4">
      <a-button
        type="primary"
        @click="openEditorDialog()"
      >
        创建规则
      </a-button>
      <a-select
        v-model="params.action"
        :options="[{ label: '全部执行策略', value: 0 }, ...executionOptions]"
        class="h-8 w-136px!"
        placeholder="请选择"
        @change="run()"
      />
      <multiple-condition-search
        v-model="params"
        :schema="searchSchema"
        @search="run"
      />
      <div class="flex-1" />
      <a-button
        class="ml-auto shrink-0 text-color-1"
        type="outline"
        :disabled="loading"
        @click="run"
      >
        <template #icon>
          <i-icons-refresh :class="{ 'animate-spin': loading }" />
        </template>
      </a-button>
    </div>
    <a-table
      ref="tableRef"
      v-bind="commonTableProps"
      :columns="tableColumns"
      :data="data"
      @sorter-change="onSorterChange"
    >
      <template #sort>
        <i-icons-draggable class="drag-icon" />
      </template>
      <template #execution="{ record }">
        <section class="flex items-center gap-x-1">
          <i-icons-prevent v-if="record.action === A_EXECUTION_TYPE.PREVENT" />
          <i-icons-observe v-else />
          {{ getOptionsLabel(executionOptions, record.action) }}
        </section>
      </template>
      <template #status="{ record }">
        <a-switch
          :model-value="record.status"
          :checked-value="1"
          :unchecked-value="2"
          size="small"
          :before-change="(val: number) => handleBeforeChange(val, record)"
        />
      </template>
      <template #node_bind_count="{ record }">
        {{ record.node_bind_count || 0 }}
      </template>
      <template #actions="{ record }">
        <a-link
          :hoverable="false"
          @click="openEditorDialog(record)"
        >
          <i-icons-edit size="16px" />
        </a-link>
        <a-popover
          title=""
          content-class="!p-1 !mt-2"
        >
          <i-icons-more
            size="16px"
            class="cursor-pointer text-[#00A65B]"
          />
          <template #content>
            <section class="flex flex-col">
              <a-link
                :hoverable="false"
                class="popover-link !text-[#1D2129]"
                @click="openDeployDialog({ id: record.id, name: record.name })"
              >
                <i-icons-deploy size="16px" />
                <span>部署</span>
              </a-link>
              <a-link
                :hoverable="false"
                status="danger"
                class="popover-link text-[#FA5566]"
                @click="handleDelete(record)"
              >
                <i-icons-delete size="16px" />
                <span>删除</span>
              </a-link>
            </section>
          </template>
        </a-popover>
      </template>
    </a-table>
    <editor-dialog
      v-model:visible="editorDialogVisible"
      :record="editorDialogData"
      @refresh="run"
    />
    <node-deploy
      v-if="deployDialogVisible"
      v-model:visible="deployDialogVisible"
      :record="deployDialogData"
      @refresh="run"
    />
  </main-container>
</template>

<style lang="less" scoped>
:deep(.arco-table-th) {
  background-color: #fff !important;
}
.popover-link {
  @apply !flex items-center !justify-start gap-x-[10px] w-[112px] h-8 !px-2  cursor-pointer hover:bg-[#F7F8FA] rounded;
}
</style>
